package com.wocai.jrt.admin.user.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.admin.common.bean.Node;
import com.wocai.jrt.admin.user.model.Roles;
import com.wocai.jrt.admin.user.model.RolesBean;
import com.wocai.jrt.admin.user.model.RolesBean.Criteria;
import com.wocai.jrt.admin.user.model.User;
import com.wocai.jrt.admin.user.service.spi.RolesService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 角色表控制器
 * @author yinlei
 * @date 2015-7-6 11:40:41
 */
@Controller
@RequestMapping("/roles")
public class RolesAction extends GenericAction<Roles> {
	private static final Logger LOGGER = LoggerFactory.getLogger(RolesAction.class);
	
	@Inject
	private RolesService rolesServiceImpl;
	
	/**
     * 跳转到角色list页。
     * @param model 参数
     * @return 角色list页
     */
    @RequestMapping("/list")
    public String list(Roles model, Map<String, Object> maps) {
        return "roles/list";
    }
	
    /**
     * 查询角色，以及初始化列表页面
     * @param role 参数
     * @return 查询结果
     */
    @ResponseBody
    @RequestMapping("/query")
    public Map<String, Object> query(@RequestBody Roles role) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		RolesBean params = buildQuery(role);
    		List<Roles> list = rolesServiceImpl.queryForList(params);
    		
    		params.setStart(null);
    		int totalRecord = rolesServiceImpl.count(params);
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("roles query success.");
    		}
    		
    		// jQuery datatable 就是这样的参数，阿西吧
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("roles query error, msg=[{}]", e.getMessage());
		}
        return result;
    }
    
    private RolesBean buildQuery(Roles role) {
    	RolesBean rolesBean = new RolesBean();
    	rolesBean.setPageSize(role.getPageSize());
    	rolesBean.setStart(role.getStart());
    	rolesBean.setDistinct(role.isDistinct());
    	
		Criteria criteria = rolesBean.createCriteria();
		
		String roleName = role.getRoleName();
		if (StringUtils.isNotBlank(roleName)) {
			criteria.andRoleNameLike(roleName);
		}
		
		Integer enabled = role.getEnabled();
		if (enabled != null) {
			criteria.andEnabledEqualTo(enabled);
		}
		
		criteria.andOrgIdEqualTo(UserUtils.getOrgId());
		return rolesBean;
    }
    
    
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add() {
        return "roles/add";
    }
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody Roles model) {
    	JsonBean bean = new JsonBean();
    	try {
    		model.setOrgId(UserUtils.getOrgId());
    		int result = rolesServiceImpl.saveRoles(model);
    		if (result == 1) {
    			bean.setMessage(SUCCESS);
    			bean.setCode(1);
    		} else {
    			bean.setMessage(ERROR);
    			LOGGER.error("save roles and relation error.");
    		}
		} catch (Exception e) {
			bean.setMessage(ERROR);
			LOGGER.error(e.getMessage());
		}
        return bean;
    }
    
    /**
     * 查看角色表详情页。
     * @param model 查询参数，携带ID
     * @return 角色表详情页
     */
    @ResponseBody
    @RequestMapping("/tree")
    public Node tree(User model) {
    	Node root = null;
    	try {
			root = rolesServiceImpl.getRoleTree(model);
		} catch (Exception e) {
			LOGGER.error("query role's tree error. msg=[{}].", e.getMessage());
		}
        return root;
    }
    
    /**
     * 获取要修改的Roles数据
     * @param model 查询参数，携带ID
     * @return 待修改的Roles
     */
    @ResponseBody
    @RequestMapping("/edit")
    public Roles edit(Roles model) {
    	String roleId = model.getRoleId();
    	if (StringUtils.isBlank(roleId)) {
    		LOGGER.error("param's roleId is null.");
    		return null;
    	}
    	try {
    		model = rolesServiceImpl.get(roleId);
		} catch (Exception e) {
			LOGGER.error("query role error, id=[{}], msg=[{}].", roleId, e.getMessage());
		}
        return model;
    }
    
    /**
     * 更新角色表信息
     * @param model 要更新的角色表信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody Roles model) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(model.getRoleId())) {
    		bean.setMessage("param's roleId cannot be null.");
    		LOGGER.error("param's roleId is null.");
    		return bean;
    	}
    	try {
    		int result = rolesServiceImpl.updateRoles(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                LOGGER.info("update roles success.");
            } else {
                bean.setMessage("update roles error.");
                LOGGER.info("update roles error, id=[{}].", model.getRoleId());
            }
		} catch (Exception e) {
			LOGGER.error("update roles error, msg=[{}].", e.getMessage());
			bean.setMessage("update roles error.");
		}
        return bean;
    }
    
    /**
     * 删除角色表信息
     * @param id 要删除的角色表ID
     */
    @ResponseBody
    @RequestMapping("/delete")
    public JsonBean delete(String id) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(id)) {
    		bean.setMessage("param's id cannot be null.");
    		return bean;
    	}
    	try {
    		int result = rolesServiceImpl.deleteRoles(id);
    		if (result == 1) {
    			bean.setMessage(SUCCESS);
    			bean.setCode(1);
    		} else {
    			LOGGER.error("delete role error, id=[{}].", id);
    			bean.setMessage(ERROR);
    		}
		} catch (Exception e) {
			LOGGER.error("delete role error, id=[{}], msg=[{}].", id, e.getMessage());
			bean.setMessage("delete role error.");
		}
        return bean;
    }
}
